package com.fjec.common.wx;

import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.WechatException;
import com.fjec.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import java.util.Map;

@Slf4j
public class WxJsApiTicketHelper {

    private WxAccessTokenHelper wxAccessTokenHelper;

    public WxJsApiTicketHelper(WxAccessTokenHelper wxAccessTokenHelper) {
        this.wxAccessTokenHelper = wxAccessTokenHelper;
    }

    /**
     * 微信文档：https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115&t=0.7027178684149746#62
     * 生成JsApiTicket
     *
     * @return
     */
    @Cacheable(cacheNames = "c_120", key = "'JsApiTicket'")
    public String getJsApiTicket() {
        return doGetJsApiTicket();
    }

    @CachePut(cacheNames = "c_120", key = "'JsApiTicket'")
    public String cacheJsApiTicket() {
        return doGetJsApiTicket();
    }

    public String doGetJsApiTicket() {
        String accessToken = wxAccessTokenHelper.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        String result = wxAccessTokenHelper.getOkHttp().get(url);
        if (log.isDebugEnabled()) {
            log.debug("请求微信JsApiTicket 返回结果=" + result);
        }
        Map<String, Object> map = JsonUtil.jsonToMap(result);
        //判断返回结果是否错误
        Integer errorCode = (Integer) map.get("errcode");
        if (errorCode == null || errorCode.intValue() != 0) {
            throw new WechatException(EnumSysCode.ERR_0023, MapUtils.getString(map, "errcode"),
                    MapUtils.getString(map, "errmsg"));
        }
        String jsApiTicket = MapUtils.getString(map, "ticket");
        return jsApiTicket;
    }
}
